import cgi
import os
import datamodel
import logging
from hotel_reservation_crud import HotelReservation
from datetime import datetime
from datetime import timedelta

from google.appengine.ext import db
from google.appengine.api import mail


class Mail:
############################################################################
# dispatcher methods
############################################################################
	def get(self, dispatcher):
		logging.info("Getting reservations with reminders for today")
		query = datamodel.HotelReservation.all()
		query.filter('emailReminder =', True)
		fromDate = datetime.now().date()
		logging.info("Checking for date %s", fromDate)
		query.filter('emailReminderDate =', fromDate)
		hotelReservation = query.fetch(100)
		for reservation in hotelReservation:
			logging.info("sending reminder")
			self.sendReservationMail(reservation, dispatcher)
		return None

	def encode(self, decodeType, outputObj, dispatcher):
		return None


############################################################################
# class methods
############################################################################
	def sendReservationMail(self, reservation, dispatcher):
		if not reservation.email:
			return None
		if reservation.email == "":
			return None
		logging.info("Sending email for reminder %s", str(reservation.key))
		sender="Trips Scrapbook <noreply@hotel-bookings.appspot.com>"
       		subject="Hotel Reservation Reminder"
        	to= reservation.email + "  <" + reservation.email+ ">"
		hostAndPort = dispatcher.request.headers.get('host')
		hotel = db.get(reservation.hotelKey)
		body = "Reminder about your reservation in hotel: "
		body += hotel.name
		body += "<br>"
		body += "<a href='http://"+hostAndPort+"/index.html'>Trip Scrapbook</a><br>"
		mail.send_mail(sender, to, subject, body, html = body)
